from starlette.endpoints import HTTPEndpoint
from starlette.responses import PlainTextResponse
import logging
import config
import xml.etree.ElementTree as ET
import wx_msg_process
from utils import Switch


class CoreRoute(HTTPEndpoint):

    def __init__(self, scope):
        super().__init__(scope)
        self._logger = logging.getLogger(type(self).__name__)

    async def get(self, request):
        signature = request.query_params["msg_signature"]
        echo_str = request.query_params["echostr"]
        timestamp = request.query_params["timestamp"]
        nonce_str = request.query_params["nonce"]
        if wx_msg_process.verify_signature_enterprise(signature, timestamp, nonce_str, echo_str, config.ENT_APP_TOKEN):
            self._logger.info("微信回调验证成功。")
            decrypt_echostr = wx_msg_process.decrypt_message(echo_str, config.ENT_APP_ENCRYPT_KEY)
            self._logger.debug(decrypt_echostr)
            return PlainTextResponse(decrypt_echostr)
        else:
            self._logger.warning("微信回调验证失败，签名不符。")
            return PlainTextResponse("Invalid Request")

    async def post(self, request):
        request_body = await request.body()
        parsed_body = ET.fromstring(request_body)

        signature = request.query_params["msg_signature"]
        timestamp = request.query_params["timestamp"]
        nonce_str = request.query_params["nonce"]
        encrypted_message = parsed_body.findtext("Encrypt")

        self._logger.debug(f"消息签名是{signature}")
        self._logger.debug(f"已加密消息是{encrypted_message}")

        if wx_msg_process.verify_signature_enterprise(signature, timestamp, nonce_str, encrypted_message,
                                                      config.ENT_APP_TOKEN):
            self._logger.debug("接收到的消息验证成功。")
            decrypted_message = wx_msg_process.decrypt_message(encrypted_message,
                                                               config.ENT_APP_ENCRYPT_KEY).decode("utf-8")
            decoded_message = ET.fromstring(decrypted_message)

            msg_type = decoded_message.findtext("MsgType").lower()

            if msg_type == "event":
                for case in Switch(decoded_message.findtext("Event").lower()):
                    if case("enter_agent"):
                        self._logger.info(f"用户{decoded_message.findtext('FromUserName')}进入了应用。")
                        break
        else:
            self._logger.info("接收到的消息验证失败。")
        return PlainTextResponse("")
